package com.yugu.park.system.service.impl;

import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yugu.park.enums.SequenceTypeEnum;
import com.yugu.park.system.entity.TSysSequence;
import com.yugu.park.system.mapper.TSysSequenceMapper;
import com.yugu.park.system.service.TSysSequenceService;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class TSysSequenceServiceImpl extends ServiceImpl<TSysSequenceMapper, TSysSequence> implements TSysSequenceService {
	@Resource
	private TSysSequenceMapper mapper;
	@Override
	public long getNext(SequenceTypeEnum ste) {
		TSysSequence tss = mapper.getByType(ste.getCode());
		if (tss == null) {
			mapper.insert(TSysSequence.builder()
                    .code(ste.getCode())
                    .name(ste.getDesc())
                    .currentVal(1l)
                    .increment(1)
                    .currentDatetime(new Date())
                    .build());
            return 1;
        }
        Date updateTime = tss.getCurrentDatetime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String format = sdf.format(updateTime);
        String format1 = sdf.format(new Date());
        long currentValue = tss.getCurrentVal();
        if(!format1.equals(format)){
            currentValue=1;
        }else{
            currentValue+=1;
        }
        tss.setCurrentVal(currentValue);
        tss.setCurrentDatetime(new Date());
        mapper.updateById(tss);
        return currentValue;
	}
	@Override
	public long getNextNoTime(SequenceTypeEnum ste ) {
		TSysSequence tss = mapper.getByType(ste.getCode());
		if (tss == null) {
			mapper.insert(TSysSequence.builder()
                    .code(ste.getCode())
                    .name(ste.getDesc())
                    .currentVal(1l)
                    .increment(1)
                    .currentDatetime(new Date())
                    .build());
            return 1;
        }
//        Date updateTime = tss.getCurrentDatetime();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//        String format = sdf.format(updateTime);
//        String format1 = sdf.format(new Date());
        long currentValue = tss.getCurrentVal() + 1;
//        if(!format1.equals(format)){
//            currentValue=1;
//        }
        tss.setCurrentVal(currentValue);
        tss.setCurrentDatetime(new Date());
        mapper.updateById(tss);
        return currentValue;
	}
}
